<?php

/**
 * Created by PhpStorm.
 * User: allen_ios
 * Date: 16/11/30
 * Time: 下午7:36
 */
namespace Task\Core;

class BaseInterf
{
    const INTERF_URL = 'http://10.251.0.62/services/thirdSdkService?wsdl';
    protected static $webServiceClient;    //webservice类的客户端

    /**
     * 访问接口的通用方法
     * @param string $funcName 方法名称
     * @param array $params 参数名,数组形式传输
     * @return array 返回数组
     */
    public static function callInter($funcName, $params)
    {
        //采用SOAP方式来进行访问的webService
        self::$webServiceClient = new \SoapClient(self::INTERF_URL);
        $paramsXml = self::arrayToXml($params);
        $returnData = self::$webServiceClient->$funcName(array('xml' => $paramsXml));
        return self::xmlToArray($returnData->return);
    }

    /**
     * 获得服务接口的登陆id
     */
    public static function getLoginSessId()
    {
        $sessionId = RedisService::get('call_webservice_sessionId');
        if ($sessionId) {   //如果redis中的sessionId已经存在
            return $sessionId;
        }

        //请求接口,然后将sessionId设置到redis中去
        $params = config('loginInfo');
        $res = self::callInter('userLogin',$params);
        if($res['head']['errorCode'] == 0 && $res['head']['result']){
            $sessionId = $res['body']['item']['sessionId'];
            RedisService::set('call_webservice_sessionId', $sessionId,1800);
            return !empty($sessionId) ? $sessionId : false;
        }
        return false;
    }

    protected static function arrayToXml($array)
    {
        $xml = "<root>";
        foreach ($array as $key => $val) {
            $xml .= "<" . $key . ">$val</" . $key . ">";
        }
        $xml .= "</root>";
        return $xml;
    }

    protected static function xmlToArray($xml)
    {
        // 将XML转为array
        $arrData = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arrData;
    }

    protected static function objToArray($obj)
    {
        $arrData = json_decode(json_encode($obj), true);
        return $arrData;
    }
}
